package handlers

import (
	"car-s/cache"
	"car-s/models"
	"car-s/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名或密码为空",
		})
		return
	}

	redis_key := "login_error" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名查询失败",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账户或密码错误",
		})
		return
	}

	if user.Password != pkg.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func RoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.rid = roles.id
		WHERE
		  user_roles.uid = 1
	*/
	var role []models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid = ?", uid).
		Find(&role)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": role,
	})
	return
}

func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/
	var node []models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid = ?", rid).
		Find(&node)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": node,
	})
	return
}

func CarAdd(c *gin.Context) {
	car_name := c.PostForm("car_name")
	car_price, _ := strconv.Atoi(c.PostForm("car_price"))

	data := models.Car{
		CarName:  car_name,
		CarPrice: car_price,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func OrderAdd(c *gin.Context) {
	order_code := c.PostForm("order_code")
	cid, _ := strconv.Atoi(c.PostForm("cid"))

	data := models.Order{
		OrderCode: order_code,
		Cid:       cid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	/*
		SELECT
		  orders.id AS OrderID,
		  orders.order_code AS OrderCode,
		  orders.cid AS Cid,
		  cars.car_name AS CarName,
		  cars.car_price AS CarPrice
		FROM
		  orders
		  LEFT JOIN cars ON cars.id = orders.cid
	*/
	var carOrder []models.CarOrder

	redis_key := "order_list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Joins("LEFT JOIN cars ON cars.id = orders.cid").
			Select(
				"orders.id AS OrderID",
				"orders.order_code AS OrderCode",
				"orders.cid AS Cid",
				"cars.car_name AS CarName",
				"cars.car_price AS CarPrice",
			).
			Offset(offset).Limit(size).Find(&carOrder)
		jsonData, _ := json.Marshal(carOrder)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &carOrder)
	}

	var total int64
	models.DB.Model(&models.Order{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  carOrder,
		"total": total,
	})
	return
}

func OrderDetail(c *gin.Context) {
	id := c.Query("id")
	/*
		SELECT
		  orders.id AS OrderID,
		  orders.order_code AS OrderCode,
		  orders.cid AS Cid,
		  cars.car_name AS CarName,
		  cars.car_price AS CarPrice
		FROM
		  orders
		  LEFT JOIN cars ON cars.id = orders.cid
	*/
	var carOrder models.CarOrder

	redis_key := "order_list_id_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Joins("LEFT JOIN cars ON cars.id = orders.cid").
			Select(
				"orders.id AS OrderID",
				"orders.order_code AS OrderCode",
				"orders.cid AS Cid",
				"cars.car_name AS CarName",
				"cars.car_price AS CarPrice",
			).
			Where("orders.id = ?", id).Find(&carOrder)
		jsonData, _ := json.Marshal(carOrder)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &carOrder)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": carOrder,
	})
	return
}
